import { defineStore } from 'pinia'
import type { IDialog, IHandleApi, IStatsChart } from 'vue3-common/types'
import { ElMessage } from 'element-plus'
import { IKpi, IKpiQuery } from '@/types/kpi'
import { addKpiApi, deleteKpiApi, queryKpiApi, updateKpiApi } from '@/apis/kpi'

export const useKpiStore = defineStore('kpi', {
  state: () => ({
    kpiList: [] as IKpi[],
    queryInfo: {
      startDate: '',
      endDate: ''
    } as IKpiQuery,
    kpiApiType: 'ADD' as IHandleApi,
    categoryStats: {} as IStatsChart[],
    currentKpi: {
      id: 0,
      date: '',
      patientName: '',
      project: '',
      price: 0
    } as IKpi,
    kpiDialog: {
      visible: false,
      title: '',
      data: {}
    } as IDialog<IKpi>,
    isRefresh: false
  }),
  actions: {
    async queryKpiList() {
      this.kpiList = await queryKpiApi(this.queryInfo)
    },
    async handleKpiApi(kpi: IKpi) {
      switch (this.kpiApiType) {
        case 'ADD':
          await addKpiApi(kpi)
          ElMessage.success('新增绩效成功')
          break
        case 'UPDATE':
          await updateKpiApi(kpi.id as number, kpi)
          ElMessage.success('更新绩效成功')
          break
        case 'DELETE':
          await deleteKpiApi(kpi.id as number)
          ElMessage.success('删除绩效成功')
          break
        default:
          break
      }
      this.kpiDialog.visible = false
      await this.refreshInfo()
    },
    async refreshInfo() {
      await this.queryKpiList()
      this.isRefresh = !this.isRefresh
    },
    getEmptyKpi(): IKpi {
      return {
        date: '',
        patientName: '',
        price: 0,
        project: ''
      }
    }
  }
})
